package com.nine.mq.config;

import com.nine.mq.config.constanst.MqConstanst;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 死信队列配置类
 */
@Configuration
public class DlxConfig {


    /**************************** 延迟队列和交换机 **********************************************************/


    // 延迟交换机
    @Bean
    public Exchange delayExchange() {
        // 属性参数：交换机名称、交换机类型、是否持久化、是否自动删除、参数
        return new DirectExchange(MqConstanst.DELAY_EXCHANGE, true, false);
    }

    // 延迟队列绑定
    @Bean
    public Binding delayBinding() {
        return BindingBuilder.bind(delayQueue()).to(delayExchange()).with(MqConstanst.DELAY_ROUTING_KEY).noargs();
    }

    // 延迟队列
    @Bean
    public Queue delayQueue() {
        // 死信交换机和路由键【绑定的是不会消费，直接到期的队列】
        //Map<String, Object> args = new HashMap<>();
        //args.put("x-dead-letter-exchange", MqConstanst.DLX_EXCHANGE);
        //args.put("x-dead-letter-routing-key", MqConstanst.DLX_ROUTING_KEY);
        //args.put("x-message-ttl", 30000);
        //return new Queue(MqConstanst.DELAY_QUEUE_NAME, true, false, false, args);
        return QueueBuilder.durable(MqConstanst.DELAY_QUEUE_NAME)
                .deadLetterExchange(MqConstanst.DLX_EXCHANGE)
                .deadLetterRoutingKey(MqConstanst.DLX_ROUTING_KEY)
                .ttl(30000).build();
    }


    /**************************** 死信队列和交换机 **********************************************************/

    // 死信交换机
    @Bean
    public Exchange dlxExchange() {
        return ExchangeBuilder.directExchange(MqConstanst.DLX_EXCHANGE).durable(true).build();
    }

    // 死信队列绑定
    @Bean
    public Binding dlxBinding() {
        return BindingBuilder.bind(dlxQueue()).to(dlxExchange()).with(MqConstanst.DLX_ROUTING_KEY).noargs();
    }

    // 死信队列
    @Bean
    public Queue dlxQueue() {
        return new Queue(MqConstanst.DLX_QUEUE_NAME, true, false, false);
    }


}
